# -*- coding: utf-8 -*-

import abc

from ..daemonize_worker import DaemonizeWorker
from ..util import create_class_instance


class Crawler(DaemonizeWorker):

    @property
    def reaper(self):
        return self._get_component('reaper', ['new'])

    @property
    def injector(self):
        return self._get_component('injector', ['inject'])

    def _load_crawl_processor(self, name=None):
        if not name:
            if hasattr(self, 'crawl'):
                return self
            else:
                raise Exception('Missing method: %s.crawl' % self.__class__.__name__)
        else:
            if 'crawl_processors' in self._cfg and isinstance(self._cfg['crawl_processors'], dict):
                class_name = self._cfg['crawl_processors'].get(name, '')
                if not class_name:
                    raise Exception('[%s] not found in cfg:crawl_processors.' % name)

                instance = create_class_instance(class_name, {'crawler': self})
                if not hasattr(instance, 'crawl'):
                    raise Exception('Missing method: %s.crawl' % class_name)

                return instance
            else:
                raise Exception('[crawl_processors] not found in cfg.')


class CrawlProcessor(object):

    def __init__(self, params={}):
        self.crawler = params['crawler'] if 'crawler' in params else None

        self._init()

    def _init(self):
        pass

    def destroy(self):
        self.crawler = None

        self._destroy()

    def _destroy(self):
        pass

    @abc.abstractmethod
    def crawl(self, params):
        raise NotImplementedError('call to abstract method %s.crawl' % (self.__class__,))
